;$(document).ready(function(){
	
	// 场景
	var scene;
	// 渲染器对象
	var renderer;
	//创建相机对象
	var camera;
	// 鼠标对象
	var mouse;
	// 射线
	var raycaster;
	// 人物对象
	var personGroup;
	// 上一个点击对象
	var prevMesh;
	
	// 对象name对应的名称
	var objName = {
		'mesh1.002_mesh1-geometry_orig_02_-_Defaul1noCu_orig_02_-_Defaul1noCu' : '脸部',
		'mesh1.002_mesh1-geometry_male-02-1noCullingID_male-02-1noCulling.JP' :'衣服',
		'mesh2.002_mesh2-geometry_male-02-1noCullingID_male-02-1noCulling.JP' : '左脚',
		'mesh3.002_mesh3-geometry_male-02-1noCullingID_male-02-1noCulling.JP' : '右脚',
		'mesh4.002_mesh4-geometry__01_-_Default1noCulli__01_-_Default1noCulli':'脖子后面头发',
		'mesh5.002_mesh5-geometry__01_-_Default1noCulli__01_-_Default1noCulli': '脖子后面1',
		'mesh6.002_mesh6-geometry__01_-_Default1noCulli__01_-_Default1noCulli' : '脖子后面2',
		'mesh7.002_mesh7-geometry__01_-_Default1noCulli__01_-_Default1noCulli': '头前部',
		'mesh8.002_mesh8-geometry__01_-_Default1noCulli__01_-_Default1noCulli': '头后部',
		'mesh9.002_mesh9-geometry_male-02-1noCullingID_male-02-1noCulling.JP' : '左手',
		'mesh10.002_mesh10-geometry_male-02-1noCullingID_male-02-1noCulling.JP': '右手',
		
	};
	
	// 创建点
	function createPoint(parray,color,size) {
		// parray位置数组，color颜色，size大小
		var geometry = new THREE.Geometry();//声明一个空几何体对象
		for (var i = 0; i < parray.length; i++) {
			var p = new THREE.Vector3(parray[i][0],parray[i][1],parray[i][2]);
			geometry.vertices.push(p); //顶点坐标添加到geometry对象
		}
		
	    var material=new THREE.PointsMaterial({
	        color:color,
	        size:size//点对象像素尺寸
	    });//材质对象
	    return new THREE.Points(geometry,material);//点模型对象
	}
	
	// 创建线条
	function createLine (a,b,col1,col2) {
		// a，b端点坐标,col1端点1颜色，col2端点2颜色
		var geometry = new THREE.Geometry();//声明一个空几何体对象
	    var p1 = new THREE.Vector3(a[0],a[1],a[2]);//顶点1坐标
	    var p2 = new THREE.Vector3(b[0],b[1],b[2]);//顶点2坐标
	    geometry.vertices.push(p1,p2); //顶点坐标添加到geometry对象
	    
	    var color1 = new THREE.Color(col1);//顶点1颜色——红色
    	var color2 = (typeof col2 == 'number') ? new THREE.Color(col2) : color1;//顶点3颜色——蓝色 
    	geometry.colors.push(color1, color2);//顶点颜色传入几何体对象
    	
	    var material=new THREE.LineBasicMaterial({
	        vertexColors: THREE.VertexColors,//以顶点颜色为准
	    });//材质对象
	    return new THREE.Line(geometry,material);//线条模型对象
	}
	
	// 创建三点面
	function createFace3(a,b,c,v,color) {
		// a，b，c三个端点坐标，v法向量，color颜色
		var geometry = new THREE.Geometry(); //声明一个空几何体对象
	    var p1 = new THREE.Vector3(a[0],a[1],a[2]); //顶点1坐标
	    var p2 = new THREE.Vector3(b[0],b[1],b[2]); //顶点2坐标
	    var p3 = new THREE.Vector3(c[0],c[1],c[2]); //顶点3坐标
	    geometry.vertices.push(p1,p2,p3); //顶点坐标添加到geometry对象
	    var normal = new THREE.Vector3( v[0], v[1], v[2] ); //三角面法向量
	    var face = new THREE.Face3( 0, 1, 2, normal); //创建三角面
	    geometry.faces.push( face ); //三角面添加到几何体
	    var material=new THREE.MeshLambertMaterial({
	        color:color,//三角面颜色
	        side:THREE.DoubleSide//两面可见
	    });//材质对象
	    var mesh=new THREE.Mesh(geometry,material);//网格模型对象
	    return mesh;
	}
	
	// 创建四点面
	function createFace4(a,b,c,d,v,color) {
		// a，b，c，d四个端点坐标，v法向量，color颜色
    	var geometry = new THREE.Geometry(); //声明一个空几何体对象
	    var p1 = new THREE.Vector3(a[0],a[1],a[2]); //顶点1坐标
	    var p2 = new THREE.Vector3(b[0],b[1],b[2]); //顶点2坐标
	    var p3 = new THREE.Vector3(c[0],c[1],c[2]); //顶点3坐标
	    var p4 = new THREE.Vector3(d[0],d[1],d[2]); //顶点4坐标
	    geometry.vertices.push(p1,p2,p3,p4); //顶点坐标添加到geometry对象
	    
	    var normal = new THREE.Vector3( v[0], v[1], v[2] ); //三角面法向量
	    var face0 = new THREE.Face3( 0, 1, 2, normal); //创建三角面0
	    var face1 = new THREE.Face3( 0, 2, 3, normal); //创建三角面1
	    geometry.faces.push( face0,face1 ); //三角面添加到几何体
	    var material=new THREE.MeshLambertMaterial({
	        color:color,//三角面颜色
	        side:THREE.DoubleSide//两面可见
	    });//材质对象
	    var mesh=new THREE.Mesh(geometry,material);//网格模型对象
	    return mesh;
    }
	
	// 创建立方体
	function createBoxGeometry(s,p,c) {
		// s大小（长宽高），p位置，c颜色
		var box=new THREE.BoxGeometry(s[0],s[1],s[2]);//创建一个立方体几何对象
		var material = new THREE.MeshLambertMaterial({color:c}); //材质对象
		var mesh= new THREE.Mesh(box,material);//网格模型对象
		mesh.translateX(p[0]);
	    mesh.translateY(p[1]);
	    mesh.translateZ(p[2]);
		return mesh;
	}
	
	// 创建圆柱体
	function createCylinderGeometry(opt,p,c) {
		// opt配置，p位置，c颜色
		//圆台(顶部半径20，底部半径40，高度100，圆周细分数40)
		var box=new THREE.CylinderGeometry(opt[0],opt[1],opt[2],opt[3]); 
		var material = new THREE.MeshLambertMaterial({color:c}); //材质对象
		var mesh= new THREE.Mesh(box,material);//网格模型对象
		mesh.translateX(p[0]);
	    mesh.translateY(p[1]);
	    mesh.translateZ(p[2]);
		return mesh;
	}
	
	// 创建球体
	function createSphereGeometry(r,p,c) {
		//r半径，p位置，c颜色
		//球体(半径60，细分数40,40)
		var sphere=new THREE.SphereGeometry(r,40,40);//创建一个球体几何对象
	    var sphereMaterial=new THREE.MeshLambertMaterial({color:c});//材质对象
	    var spereMesh=new THREE.Mesh(sphere,sphereMaterial);//网格模型对象
	    spereMesh.translateX(p[0]);
	    spereMesh.translateY(p[1]);
	    spereMesh.translateZ(p[2]);
		return spereMesh;
	}
	
	// 渲染
	function render() {
        renderer.render(scene,camera);//执行渲染操作
    }
	
	function init() {
		
		// 初始化场景
		scene = new THREE.Scene();
		raycaster = new THREE.Raycaster();
		mouse =  new THREE.Vector2();
		
		// 光源设置
		var point=new THREE.PointLight(0xffffff); 
		point.position.set(400,200,300);//点光源位置
		scene.add(point);//点光源添加到场景中
		//环境光
		var ambient=new THREE.AmbientLight(0x444444);
		scene.add(ambient);
		
		// 相机设置
		var width = window.innerWidth;//窗口宽度
		var height = window.innerHeight;//窗口高度
		var k = width/height;//窗口宽高比
		var s = 130;//三维场景缩放系数
		camera=new THREE.OrthographicCamera(-s*k,s*k, s,-s,1,1000);
		camera.position.set(400,200,400);//设置相机位置
		camera.lookAt(scene.position);//设置相机方向(指向的场景对象)
		
		// 渲染器设置
		renderer=new THREE.WebGLRenderer()
		renderer.setSize(width,height);
		renderer.setClearColor(0xfcfcfc,1);//设置背景颜色
		document.body.appendChild(renderer.domElement);//body元素中插入canvas对象
		
	    var controls = new THREE.OrbitControls(camera);//创建控件对象
		controls.addEventListener('change', render);//监听鼠标、键盘事件
		
		// 创建立方体
		var mesh = createBoxGeometry([80,20,100],[0,-100,0],0xcccccc);
		mesh.userData.name = '立方体';
		scene.add(mesh);//网格模型添加到场景中
		
		//圆柱体
		var mesh = createCylinderGeometry([15,15,30,40],[0,0,-80],0xcccccc);
		mesh.userData.name = '圆柱体';
		scene.add(mesh);//网格模型添加到场景中
		
		// 创建球体
	    var mesh = createSphereGeometry(15,[-80,0,0],0x0099CC);
	    mesh.userData.name = '球1';
	    scene.add(mesh);//网格模型添加到场景中
	    
		// 创建线条对象
	    var line1 = createLine([-500,0,0],[500,0,0],0x0000ff);
	    var line2 = createLine([0,-500,0],[0,500,0],0x00ff00);
	    var line3 = createLine([0,0,-500],[0,0,500],0xff0000);
	    scene.add(line1,line2,line3);//线条对象添加到场景中
	    
	    // 创建点圆柱体
	    var mesh1 = createCylinderGeometry([0,2,5,40],[100,0,0],0x0000ff);
	    var mesh2 = createCylinderGeometry([0,2,5,40],[0,120,0],0x00ff00);
	    var mesh3 = createCylinderGeometry([0,2,5,40],[0,0,100],0xff0000);
	    mesh1.rotateZ(-Math.PI/2);
	    mesh3.rotateX(Math.PI/2);
	    //var points = createPoint([[100,0,0],[0,100,0],[0,0,100]],0x000000,10.0);
	    scene.add(mesh1,mesh2,mesh3);
	    
	    // 模型
	    // 加载进度回调
		var onProgress = function ( xhr ) {
			if ( xhr.lengthComputable ) {
				var percentComplete = xhr.loaded / xhr.total * 100;
				console.log( Math.round(percentComplete, 2) + '% downloaded' );
			}
		};
		// 加载错误回调
		var onError = function ( xhr ) { };
		THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
		var mtlLoader = new THREE.MTLLoader();
		mtlLoader.setPath( 'plugin/threejs/models/obj/male02/' );
		mtlLoader.load( 'male02_dds.mtl', function( materials ) {
			materials.preload();
			var objLoader = new THREE.OBJLoader();
			objLoader.setMaterials( materials );
			objLoader.setPath( 'plugin/threejs/models/obj/male02/' );
			objLoader.load( 'male02.obj', function ( object ) {
				object.position.y = - 90;
				object.rotateY(Math.PI/2);
				personGroup = object;
				
				// 克隆每个模型的材质，防止使用同一个对象带来的高亮影响
				for (var i = 0; i < personGroup.children.length; i++) {
					var obj = personGroup.children[i];
					obj.material = obj.material.clone();
				}
				
				scene.add( object );
				render();
			}, onProgress, onError );
		});
	    
	    //执行渲染操作
		render();
		
		initBind();
	}
	
	// 映射obj对象
	function intersetModelObj() {
		if (!personGroup) {
			return true;
		}
		var intersects = raycaster.intersectObjects( personGroup.children );
		if ( intersects.length > 0 ) {
			
			// 还原原来的颜色
			if (prevMesh) {
				prevMesh.material.color.r = prevMesh.userData.prevColor.r;
				prevMesh.material.color.g = prevMesh.userData.prevColor.g;
				prevMesh.material.color.b = prevMesh.userData.prevColor.b;
			}
			
			// 记录当前点击对象
			var firstD = intersects[ 0 ];
			var obj = firstD.object;
			
			prevMesh = obj;
			prevMesh.userData.prevColor = {
				'r':obj.material.color.r,
				'g':obj.material.color.g,
				'b':obj.material.color.b,
			};
			// 高亮
			obj.material.color.setHex(0xff0000 );
			
			// 显示框
			var curname = objName[obj.name] || obj.name;
			$("#tipdiv").html(curname);
			
			//移除之前的线和端点
			var oldP = scene.getChildByName('showPoint');
			scene.remove(oldP);
			var oldL = scene.getChildByName('showLine');
			scene.remove(oldL);
			
			// 计算两个端点
			var x = firstD.point.x;
			var y = firstD.point.y;
			var z = firstD.point.z;
			var r = 40;
			var p1 = [x,y,z];
			var p2 = [x<0?x-r:x+r,y<0?y-r:y+r,z<0?z-r:z+r];
			
			// 端点
			var spereMesh = createSphereGeometry(4,p2,0x0099CC);
			spereMesh.name = 'showPoint';
			spereMesh.userData.info = obj.name;
    		scene.add(spereMesh);
    		
    		// 线
    		var line = createLine(p1,p2,0xff0000);
    		line.name = 'showLine';
    		scene.add(line);
		}
	}
	
	// 映射圆点
	function intersetToolObj() {
		var intersects = raycaster.intersectObjects( scene.children );
		if ( intersects.length > 0 ) {
			
			var firstD = intersects[ 0 ];
			var obj = firstD.object;
			if (obj.name == 'showPoint') {
				var name = objName[obj.userData.info] || obj.userData.info;
				if (confirm('是否打开'+name+'的详细数据？')) {
					window.location.href = 'http://www.baidu.com';
				}
			}
			
		}
	}
	
	// 绑定事件
	function initBind() {
		// 鼠标点击
		document.addEventListener( 'mousedown', function(){
			
			event.preventDefault();
			mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
			mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
			raycaster.setFromCamera( mouse, camera );
			
			intersetModelObj();
			intersetToolObj();
			
			render();
		}, false );
	}
	
	init();
	
});
